<!--
 * @Author: yanjikun
 * @Date: 2021-06-18 14:32:59
 * @LastEditors: yanjikun
 * @LastEditTime: 2022-05-31 11:58:40
 * @Description: file content
-->
<template>
  <Menu
    :openKeys="openKeys"
    v-model:selectedKeys="selectedKeys"
    mode="inline"
    @click="handleClickMenu"
    theme="light"
  >
    <template v-for="item in menus" :key="item.name">
      <MenuItem :menu-info="item"></MenuItem>
    </template>
  </Menu>
</template>

<script lang="ts" setup>
  import { Menu } from 'ant-design-vue'
  import MenuItem from './menu-item.vue'
  import { useRoute } from 'vue-router'
  import router from '@/router'
  import { computed, ref, unref, watch } from 'vue'
  import { Key } from 'ant-design-vue/lib/_util/type'
  import { MenuClickEventHandler } from 'ant-design-vue/lib/menu/src/interface'
  import { useUserStore } from '@/store/modules/user'
  import { isUrl } from '@/utils/is'
  import { LOGIN_PATH } from '@/router/constant'
  defineOptions({
    name: 'YMenu',
  })
  const userStore = useUserStore()
  const route = useRoute()

  const menus = computed(() => userStore.getMenus())
  const getOpenKeys = () => {
    const meta = route.meta
    if (meta?.hidden) {
      return unref(openKeys) ?? []
    }
    const path = route.path.split('/').slice(1)
    return path.map((_item, index) => {
      let name = ''
      for (let i = 0; i < index + 1; i++) {
        name += `/${path[i]}`
      }
      return name
    })
  }
  const openKeys = ref<string[]>([])
  const selectedKeys = ref([route.name] as Key[])
  const props = defineProps({
    collapsed: {
      type: Boolean,
    },
  })
  // 跟随页面路由变化，切换菜单选中状态
  watch(
    () => route.fullPath,
    () => {
      if (route.name == LOGIN_PATH || props.collapsed) return
      openKeys.value = getOpenKeys()
      selectedKeys.value = [route.name] as Key[]
    },
    {
      immediate: true,
    },
  )
  watch(
    () => props.collapsed,
    (newValue) => {
      openKeys.value = newValue ? [] : getOpenKeys()
      selectedKeys.value = [route.name] as Key[]
    },
  )
  const handleClickMenu: MenuClickEventHandler = (menuInfo) => {
    const key = menuInfo.key as string
    if (isUrl(key)) {
      window.open(key)
    } else {
      router.push({ name: key })
    }
  }
</script>
